﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.Admin;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NetDon.OA.Portal;
using NetDon.WebControls;
using NineRays.WebControls;

namespace NetDon.OA.Portal.Admin
{
    [Navigation("系统管理", "用户管理")]
    public partial class UserManage : PageBase
    {
        public Guid? CompanyId
        {
            get
            {
                return treeOrganization.CompanyId;
            }

        }
        public Guid DepartmentId
        {
            get
            {
                return treeOrganization.DepartmentId;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            treeOrganization.LoadItems += this.btnModify_Click;
            if (!IsPostBack)
            {
                dplUserStatus.SelectedValue = UserStatus.Active.ToString();
                PagerUsers.PerformQuery();
                btnCreateNew.OnClientClick = string.Format("createOreditUser();return false;");
            }
        }


        protected void PagerUsers_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            var service = ServiceContainer.GetService<IUserService>();
            e.DataSource = service.SearchUsers((UserSearchCriteria)e.Condition,
                                                          gridUsers.SortExpression, gridUsers.SortDirection, e.PageSize,
                                                          e.PageIndex);
        }

        protected void PagerUsers_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IUserService>();
            e.RecordCount = service.GetUserCount(
                                                 (UserSearchCriteria)e.Condition);
        }

        protected void PagerUsers_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new UserSearchCriteria
            {
                UserName = txtLoginName.Text.Trim(),
                Email = txtEmail.Text.Trim(),
                FullName = txtFullName.Text.Trim()
            };

            if (!string.IsNullOrEmpty(dplUserType.SelectedValue))
            {
                criteria.UserType = dplUserType.SelectedValue.ToEnum<UserType>();
            }

            if (!string.IsNullOrEmpty(dplUserStatus.SelectedValue))
            {
                criteria.Status = dplUserStatus.SelectedValue.ToEnum<UserStatus>();
            }

            if (!string.IsNullOrEmpty(ddlPosition.SelectedValue))
            {
                criteria.PositionId = ddlPosition.SelectedValue.ToGuid();
            }

            if (CompanyId.HasValue && CompanyId.Value != Guid.Empty)
            {
                criteria.CompanyId = CompanyId;
            }
            if (DepartmentId != Guid.Empty)
            {
                criteria.DepartId = DepartmentId;
            }
            e.Condition = criteria;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PagerUsers.PerformQuery();
        }
        protected void btnReload_Click(object sender, EventArgs e)
        {
            PagerUsers.ReloadCurrentPage();
        }
        protected void gridUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var userId = (Guid)DataBinder.Eval(e.Row.DataItem, UserFields.UserId.Name);
                e.Row.Attributes["UserId"] = userId.ToString();

                var btnActivate = (ImageButton)e.Row.FindControl("btnActivate");
                if (btnActivate != null)
                {
                    btnActivate.OnClientClick =
                        "activateUser('{0}');return false;".Formato(userId);
                }
                var btnUnActivate = (ImageButton)e.Row.FindControl("btnUnActivate");
                if (btnUnActivate != null)
                {
                    btnUnActivate.OnClientClick =
                        "unActivateUser('{0}');return false;".Formato(userId);
                }
                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = "modifyOreditUser('{0}','{1}','{2}');return false;".Formato(userId, CompanyId.HasValue ? CompanyId.Value : Guid.Empty, DepartmentId);
                }
                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                btnDelete.OnClientClick = "deleteUser('{0}');return false;".Formato(userId);

            }
        }
        protected void btnModify_Click(object sender, EventArgs e)
        {
            PagerUsers.PerformQuery();
        }

        protected void btnActivation_Click(object sender, EventArgs e)
        {
            Guid userId = fieldUserId.Value.ToGuid();
            var transaction = new Transaction(IsolationLevel.ReadCommitted, "Activate User");
            try
            {
                var userEntity = new UserEntity(userId);
                userEntity.UserStatus = (int)UserStatus.Active;

                transaction.Add(userEntity);
                userEntity.Save();
               
                transaction.Commit();
                PagerUsers.PerformQuery();
                Success("用户成功激活，现在可以登录。");

            }
            catch (Exception)
            { // Alert("Can not delete the product. Since it's in use of orders.");
                Alert("用户激活失败！");
                transaction.Rollback();
                throw;
            }
        }

        protected void btnUnActivation_Click(object sender, EventArgs e)
        {
            Guid userId = fieldUserId.Value.ToGuid();
            var transaction = new Transaction(IsolationLevel.ReadCommitted, "Not Uctivate User");
            try
            {
                var userEntity = new UserEntity(userId);
                userEntity.UserStatus = (int)UserStatus.NotActive;

                transaction.Add(userEntity);
                userEntity.Save();

                    transaction.Commit();
                    PagerUsers.PerformQuery();
        
            }
            catch (Exception)
            {
                transaction.Rollback();
                Alert("用户设置未激活失败！");
                throw;
            }
        }

        protected void btnDeleteUser_Click(object sender, EventArgs e)
        {
            var service = ServiceContainer.GetService<IUserService>();
            Guid userId = fieldUserId.Value.ToGuid();
            if (service.ValidateUserReferenced(userId))
            {
                Alert("删除失败，用户在使用中。");
            }
            else
            {
                service.RemoveUser(userId);
                PagerUsers.PerformQuery();
                Success("删除用户成功!");
            }
        }
    }
}
